/**
 * Copyright (c) 2011 Daniel Centore
 *
 * ex: set filetype=java expandtab tabstop=4 shiftwidth=4 :
 * 
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * This code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation.
 */
package wiiWired.controller.mote;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

/**
 * Class which handles a collection of all the MoteControllers
 * 
 * @author Daniel Centore
 *
 */
public class ControllerModel {

	private static List<MoteController> controller = new ArrayList<MoteController>();	//list of all current and past controllers

	/**
	 * Adds a remote to the list (should be called within the MoteController constructor)
	 * @param m
	 */
	public static synchronized void addMote(MoteController m)
	{
		if(!replaceMote(m))
			controller.add(m);
	}

	//	public static synchronized void removeMote(MoteController m)		//we dont remove motes anymore!
	//	{
	//		controller.remove(m);
	//	}

	/**
	 * Replaces an old remote with a new one with same bt adress
	 * @param after The new remote
	 * @return True if it replaced, false if the original mote didn't exist
	 */
	public static synchronized boolean replaceMote(MoteController after)
	{
		ListIterator<MoteController> iter = controller.listIterator();

		MoteController m = null;

		while(iter.hasNext())
		{
			m = iter.next();

			if(m.getBluetoothAddress().equals(after.getBluetoothAddress()))
			{
				iter.set(after);
				return true;
			}
		}

		return false;
	}

	/**
	 * Returns an array of the MoteControllers
	 * @return
	 */
	public static MoteController[] getModel()
	{
		Object[] o = controller.toArray();
		MoteController[] result = new MoteController[o.length];

		for(int i = 0; i < o.length; i++)
			result[i] = (MoteController) o[i];

		return result;
	}

	/**
	 * Sorts the remotes alphabetically by name
	 */
	public static void sortMotes()
	{
		Collections.sort(controller);
	}

}
